//
//  AnswerSortListViewController.m
//  Hxcsfw
//
//  Created by qiysoft on 2017/12/28.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "AnswerSortListViewController.h"
#import "AnswerModel.h"
#import "SBCell.h"
#define SBCellIndentifier @"SBCellIndentifier"
#import "VideoDetailViewController.h"
#import "WWebViewController.h"
#import "AFSoundManager.h"
#import "LoginViewController.h"
#import "CheckNetwork.h"

@interface AnswerSortListViewController ()<UITableViewDelegate,UITableViewDataSource,AnswerCellDelegate>
{
    SBCell *cell2;
    int j;
    BOOL BF;
    NSURL *previousURL;
    UILabel *quanJuLb;
    UIButton *quanJuBt;
    CGFloat cellTitH;
    
    NSInteger markIndex;
}

@property (nonatomic,strong) NSMutableArray *WenBaListArray;

@end

@implementation AnswerSortListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = _navTitle;
    BF = NO;
    previousURL = [NSURL URLWithString:@"http://www.sx95113.com"];
    
    // 注册控件
    UINib *cellNib2 = [UINib nibWithNibName:@"SBCell" bundle:nil];
    [self.myTableView registerNib:cellNib2 forCellReuseIdentifier:SBCellIndentifier];
    //    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:SBCellIndentifier];
    
    _WenBaListArray = [NSMutableArray array];
    [self AnswerVCDataRequest];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WBQXNOTICE) name:@"ASWBQX" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeASWBQX) name:@"LogoutSucceed" object:nil];
}

// 删除指定通知
- (void)removeASWBQX {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ASWBQX" object:nil];
}

#pragma mark - 下载列表数据
- (void)AnswerVCDataRequest {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noWifiRefershingEnd) name:REFRESHINGEND object:nil];
    
    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestListDataStrNum:@"1" isRefresh:YES];
        j = 1;
    }];
    
    //    if (kIsHaveNetwork) //有网
    //    {
    //        [_myTableView.header beginRefreshing];
    //    } //else无网
    [_myTableView.header beginRefreshing];
    
    self.myTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num isRefresh:NO];
    }];
}
- (void)noWifiRefershingEnd {
    [self.myTableView.header endRefreshing];
    [self.myTableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;

}

#pragma mark - 下载列表数据
- (void)requestListDataStrNum:(NSString *)pageNum isRefresh:(BOOL)isRefresh{
    
    //mode:native,service:fwwb,content:{revert:paginate,keyword:?,pagesize:?,pagenumber:?}
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"fwwb",@"content":@{@"revert":@"paginate",@"level":_level1,@"level2":_level2,@"level3":_level3,@"pagesize":@"10",@"pagenumber":pageNum}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
      
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        
        if (isRefresh) {
            [self.WenBaListArray removeAllObjects];
        }
        WLog(@"%@",returnDic[@"data"]);
        for (NSDictionary *dic in returnDic[@"data"]) {
            AnswerModel *answerModel = [AnswerModel mj_objectWithKeyValues:dic];
            [self.WenBaListArray addObject:answerModel];
        }
        
        [_myTableView reloadData];
        [self.myTableView.header endRefreshing];
        [self.myTableView.footer endRefreshing];
        ///* --- 图片式提醒
        UIView *view = [self.myTableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (_WenBaListArray.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.myTableView addSubview:_nonePage];
        }
        //*/
        if ([returnDic[@"data"] count] < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.myTableView.footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSError *error) {
        WLog(@"失败");
        [self.myTableView.header endRefreshing];
        [self.myTableView.footer endRefreshing];
        ///* --- 图片式提醒
        UIView *view = [self.myTableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (_WenBaListArray.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.myTableView addSubview:_nonePage];
        }
        //*/
    } showProgress:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//设置UITableViewCell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    cell2  = [[[NSBundle mainBundle] loadNibNamed:@"SBCell" owner:self options:nil] lastObject];
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;//点击不变色
    cell2.Play_Click.tag = indexPath.row;
    cell2.wenBaCellLabel.tag = indexPath.row + 111111;
    cell2.delegate = self;
    if (self.WenBaListArray.count > 0 && self.WenBaListArray != nil) {
        cell2.titleLB.text = [self.WenBaListArray[indexPath.row] title];

        [UILabel changeSpaceForLabel:cell2.titleLB];
        
        // ------ 自由行高
        CGSize maximumLbTitle = CGSizeMake(WSCREENH_WIDTH - 42, MAXFLOAT);//labelsize的最大值
        CGSize expectSize = [cell2.titleLB sizeThatFits:maximumLbTitle];
        
        if (expectSize.height == 22) {//如果单行时
            expectSize.height = 22;
        }//40

        if (expectSize.height > 60) {
            expectSize.height = 50;
        }
        
        cell2.cellTitH.constant = expectSize.height;
        cellTitH = expectSize.height;
        // ------ 自由行高
        
        cell2.fbsjLB.text = [self.WenBaListArray[indexPath.row] fbsj];
        cell2.viewLB.text = [NSString stringWithFormat:@"%@人看过",[self.WenBaListArray[indexPath.row] strView]];
        
        if ([WShareUtil strNilOrEmpty:[self.WenBaListArray[indexPath.row] audiosrc]]) {//判断有无音频字段(无)
            
            cell2.wenBaCellImang.image = [UIImage imageNamed:@"wenba_read"];
            cell2.wenBaCellLabel.text = @"点击查看";
            cell2.wenBaCellImang.hidden = YES;
            cell2.wenBaCellLabel.hidden = YES;
            
        }else{//（有）
            
            cell2.wenBaCellImang.image = [UIImage imageNamed:@"wenba_listen"];
            cell2.wenBaCellLabel.text = @"点击播放";
            
        }
        if ([[self.WenBaListArray[indexPath.row] isvip] isEqualToString:@"N"]) {
            cell2.isVip.hidden = YES;
        }else{
            //cell2.isVip.hidden = NO;//会员内容显示VIP
            cell2.isVip.hidden = YES;//都不显示VIP
            
        }
    }
    return cell2;
}

//行点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 都能进详情查看
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    WLog(@"%@===========isfees",[self.WenBaListArray[indexPath.row] isfees]);
    WLog(@"%@===========isvip",[self.WenBaListArray[indexPath.row] isvip]);
    WLog(@"%@+++++++++++strlxmc",[WShareUtil sharedData].strlxmc);
//    // 对会员不收费， 对非会员收费
//    if ([[self.WenBaListArray[indexPath.row] isfees] isEqualToString:@"Y"] && [[self.WenBaListArray[indexPath.row] isvip] isEqualToString:@"N"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc]) {
//        WLog(@"对会员不收费， 对非会员收费");
//        return;
//    }
//
//    // 对会员也收费
//    if ([[self.WenBaListArray[indexPath.row] isfees] isEqualToString:@"Y"] && [[self.WenBaListArray[indexPath.row] isvip] isEqualToString:@"Y"]) {
//        WLog(@"对会员也收费");
//        return;
//    }
//
//    // 不收费， 但只能会员听
//    if ([[self.WenBaListArray[indexPath.row] isfees] isEqualToString:@"N"] && [[self.WenBaListArray[indexPath.row] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc]) {
//        WLog(@"不收费， 但只能会员听");
//        return;
//    }

    if ([[self.WenBaListArray[indexPath.row] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc] && [WShareUtil sharedData].dicSession) {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还不是会员，加入会员即可查看!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [av show];
        return;
    }


    if ([[self.WenBaListArray[indexPath.row] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc] && ![WShareUtil sharedData].dicSession) {

        markIndex = indexPath.row;
        [WShareUtil sharedData].Who = @"ASWBQX";
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];

    } else {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"问吧详情";
        webVc.shareTitle = [self.WenBaListArray[indexPath.row] title];//分享标题
        webVc.strID = [self.WenBaListArray[indexPath.row] ID];//分享ID
        webVc.strType = @"wz";//分享类型文章

        if (![WShareUtil strNilOrEmpty:[self.WenBaListArray[indexPath.row] link]] ) {
            webVc.strUrl = [self.WenBaListArray[indexPath.row] link];
        }else{
            webVc.strUrl = [self.WenBaListArray[0] link];
        }
        [self.navigationController pushViewController:webVc animated:YES];
    }
    
}

- (void)WBQXNOTICE {

    if ([WShareUtil sharedData].dicSession) {
        [WShareUtil sharedData].strlxmc = [WShareUtil sharedData].dicSession[@"lx_mc"];
    }
    if ([[self.WenBaListArray[markIndex] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc] && [WShareUtil sharedData].dicSession) {

        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还不是会员，加入会员即可查看!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [av show];
        return;

    } else {
        WWebViewController *webVc = [[WWebViewController alloc] init];
        webVc.strTitle = @"问吧详情";
        webVc.shareTitle = [self.WenBaListArray[markIndex] title];//分享标题
        webVc.strID = [self.WenBaListArray[markIndex] ID];//分享ID
        webVc.strType = @"wz";//分享类型文章

        if (![WShareUtil strNilOrEmpty:[self.WenBaListArray[markIndex] link]] ) {
            webVc.strUrl = [self.WenBaListArray[markIndex] link];
        }else{
            webVc.strUrl = [self.WenBaListArray[0] link];
        }
        [self.navigationController pushViewController:webVc animated:YES];
    }
}


//分组个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//列表行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _WenBaListArray.count;
}

//设置行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cellTitH == 22) {//单行
        return cellTitH + 35 + 10;
    }else{
        return cellTitH + 35 + 15;//(22+41)/40+41
    }
    
}

- (void)Play_ClickBtn:(UIButton *)button {
    WLog(@"播放或详情");
    
    CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
    if (![checkNetwork isNetworkReachable]) {//没网
        return;
    } else {
        quanJuLb.text = @"正在加载";

        if (self.WenBaListArray == nil || self.WenBaListArray.count <= 0) {
            return;
        }

        WLog(@"%@===========isfees",[self.WenBaListArray[button.tag] isfees]);
        WLog(@"%@===========isvip",[self.WenBaListArray[button.tag] isvip]);
        WLog(@"%@+++++++++++strlxmc",[WShareUtil sharedData].strlxmc);

//        // 对会员不收费， 对非会员收费
//        if ([[self.WenBaListArray[button.tag] isfees] isEqualToString:@"Y"] && [[self.WenBaListArray[button.tag] isvip] isEqualToString:@"N"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc]) {
//            WLog(@"对会员不收费， 对非会员收费");
//            return;
//        }
//
//        // 对会员也收费
//        if ([[self.WenBaListArray[button.tag] isfees] isEqualToString:@"Y"] && [[self.WenBaListArray[button.tag] isvip] isEqualToString:@"Y"]) {
//            WLog(@"对会员也收费");
//            return;
//        }
//
//        // 不收费，但只能会员听
//        if ([[self.WenBaListArray[button.tag] isfees] isEqualToString:@"N"] && [[self.WenBaListArray[button.tag] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc]) {
//            WLog(@"不收费,但只能会员听");
//            return;
//        }
        
        //    NSIndexPath *indexPath1 = [_myTableView indexPathForSelectedRow];

        if ([[self.WenBaListArray[button.tag] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc] && [WShareUtil sharedData].dicSession) {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还不是会员，加入会员即可查看!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [av show];
            return;
        }


        if ([[self.WenBaListArray[button.tag] isvip] isEqualToString:@"Y"] && [WShareUtil strNilOrEmpty: [WShareUtil sharedData].strlxmc] && ![WShareUtil sharedData].dicSession) {

            markIndex = button.tag;
            [WShareUtil sharedData].Who = @"ASWBQX";
            LoginViewController *loginVc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:loginVc animated:YES];

        } else {
            WLog(@"%ld",button.tag);
            if ([WShareUtil strNilOrEmpty:[self.WenBaListArray[button.tag] audiosrc]]) {//无音频
                WLog(@"无音频跳详情");

                WWebViewController *webVc = [[WWebViewController alloc] init];
                webVc.strTitle = @"问吧详情";
                if (![WShareUtil strNilOrEmpty:[self.WenBaListArray[button.tag] link]] ) {
                    webVc.strUrl = [self.WenBaListArray[button.tag] link];
                }else{
                    webVc.strUrl = [self.WenBaListArray[0] link];
                }
                [self.navigationController pushViewController:webVc animated:YES];

            }else{//有音频

                button.selected = !button.selected;
                if (button.selected ||(![previousURL.absoluteString isEqualToString:[self.WenBaListArray[button.tag] audiosrc]] && ![WShareUtil strNilOrEmpty:previousURL.absoluteString])) {//选中
                    UILabel *find_label = (UILabel *)[self.view viewWithTag:(button.tag + 111111)];
                    find_label.text = @"正在加载";

                    [[AFSoundManager sharedManager]stop];//停播
                    WLog(@"选中");
                    WLog(@"000-%@",previousURL.absoluteString);
                    WLog(@"111-%@",[self.WenBaListArray[button.tag] audiosrc]);

                    if (![previousURL.absoluteString isEqualToString:[self.WenBaListArray[button.tag] audiosrc]] && ![WShareUtil strNilOrEmpty:previousURL.absoluteString] ) {
                        //播放音频
                        WLog(@"音频地址-%@",[self.WenBaListArray[button.tag] audiosrc]);
                        quanJuLb.text = @"点击播放";
                        [[AFSoundManager sharedManager]startStreamingRemoteAudioFromURL:[self.WenBaListArray[button.tag] audiosrc] andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
                            BF = YES;//播
                            previousURL = [NSURL URLWithString:[self.WenBaListArray[button.tag] audiosrc]];//以前url
                            UILabel *find_label = (UILabel *)[self.view viewWithTag:(button.tag + 111111)];
                            quanJuLb = find_label;
                            quanJuBt = button;
                            find_label.text = @"正在播放";

                        }];
                    }else if (button.selected ||(BF == YES && [previousURL.absoluteString isEqualToString:[self.WenBaListArray[button.tag] audiosrc]] && ![WShareUtil strNilOrEmpty:previousURL.absoluteString])){
                        [[AFSoundManager sharedManager]resume];//继续播
                        BF = NO;
                        UILabel *find_label = (UILabel *)[self.view viewWithTag:(button.tag + 111111)];
                        find_label.text = @"正在播放";
                    }
                }else {//未选中
                    WLog(@"未选中");

                    [[AFSoundManager sharedManager]pause];//暂停
                    UILabel *find_label = (UILabel *)[self.view viewWithTag:(button.tag + 111111)];
                    find_label.text = @"继续播放";
                }
            }
        }
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AFSoundManager sharedManager]pause];//暂停
    quanJuLb.text = @"继续播放";
    quanJuBt.selected = NO;
}

- (void)dealloc {
    //移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
